<template>
  <div class="chat-container">
    <div class="chat-box">
      <div class="message-area" ref="messageArea">
        <div v-for="msg in messages" :key="msg.specificRecordId" :class="['message', msg.role === 'user' ? 'user' : 'assistant']">
          <!-- 根据消息类型渲染内容 -->
          <div v-if="msg.contentType === 'image'" class="message-content">
            <VMarkdownView :mode=mode :content="`![image](${msg.content})`" />
          </div>
          <div v-if="msg.contentType === 'text'" class="message-content">
            <!-- 如果消息是用户消息，则直接渲染文本；如果是助手消息，则渲染为Markdown -->
            <div v-if="msg.role === 'user'">
              <el-text >
                {{ msg.content }}
              </el-text>
            </div>
            <div v-if="msg.role === 'assistant'">
              <VMarkdownView :mode="mode"  :highlight="highlight" :content="msg.content" /> <!-- 渲染助手消息的Markdown -->
            </div>
          </div>
        </div>


      <template class="input-area">
        <el-input type="textarea" v-model="newMessage"  :autosize="{ minRows: 2, maxRows: 4 }"
                  placeholder="请输入消息..." class="message-input" @keyup.enter="sendMessage"/>
        <el-button type="primary" @click="sendMessage" class="send-btn" plain :icon="Position">发送</el-button>
      </template>
    </div>
  </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue';
import { axiosInstance } from '@/axios';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { useRoute,useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { VMarkdownView } from 'vue3-markdown';
import 'vue3-markdown/dist/style.css'
import {Position} from "@element-plus/icons-vue";
const mode=ref("light")
const highlight=ref(true)

const store = useStore();
const route = useRoute();
const router = useRouter();
const token = localStorage.getItem('token');
const messages = ref([]); // 当前聊天的消息
const newMessage = ref(""); // 新消息输入框

// 获取消息区域的 DOM 元素
const messageArea = ref(null);
const chatId = ref(null);

// 页面加载时
onMounted(() => {

  chatId.value = route.params.historyRecordId;
  if (chatId.value != null) {
    fetchChatMessages(chatId.value);
    const initialMessage = store.getters.getMessagesByRecordId(Number(chatId.value));
    if (initialMessage && initialMessage.content && initialMessage.content.trim() !== '') {
      store.dispatch('deleteMessage', Number(chatId.value));
      saveMessage(initialMessage.content);
      chat(initialMessage.content);
      scrollToBottom();
    }

  }
});

const fetchChatMessages = (historyRecordId) => {
  axiosInstance.get("/specificRecord/listSpecificRecords?historyRecordId=" + historyRecordId, {
    headers: { token: token }
  }).then(res => {
    if (res.data.code === 100000) {
      messages.value = res.data.data;

    } else if (res.data.code===100081){
      router.push({name :'notFound-404'})
    }
  });

};

// 保存新消息
const saveMessage = (message) => {
  const specificRecord = {
    historyRecordId: chatId.value,
    content: message
  };
  axiosInstance.post('/specificRecord/save', specificRecord, {
    headers: { token: token }
  }).then(res => {
    let data = res.data;
    if (data.code === 100000) {
      messages.value.push(data.data);
    }
  });
};

// 发送消息
const chat = (message) => {
  const content = {
    content: message
  };
  axiosInstance.post('/ai/judge', content, {
    headers: { token: token }
  }).then(res => {
    let data = res.data;
    if (data.code === 100000) {
      if (data.data === 'text') {
        textChat();
      } else if (data.data === 'image') {
        imageChat(message);
      }
    }
  });
};

const imageChat = (message) => {
  const specificRecord = {
    historyRecordId: chatId.value,
    content: message,
    model: "dall-e-3"
  };
  axiosInstance.post('/ai/image', specificRecord, {
    headers: { token: token }
  }).then(res => {
    let data = res.data;
    if (data.code === 100000) {
      messages.value.push(data.data);
    }
  });
};

const textChat = () => {
  const specificRecord = {
    historyRecordId: chatId.value,
    model: "gpt-4o"
  };
  let execute = false;

  fetchEventSource('http://localhost:8080/api/v1/ai/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'token': token
    },
    body: JSON.stringify(specificRecord),
    onmessage: (event) => {
      const data = JSON.parse(event.data);
      if (data.code === 100000) {
        const newContent = data.data.content;
        if (!execute) {
          const newMessage = {
            content: newContent,
            role: "assistant",
            contentType: "text"
          };
          messages.value.push(newMessage);
          execute = true;
        }
        const encodedContent = encodeURIComponent(newContent);
        messages.value[messages.value.length - 1].content += decodeURIComponent(encodedContent);

        // 确保页面滚动到底部
        nextTick(() => {
          scrollToBottom();
        });
      }
    },
    onerror: (error) => {
      console.error('SSE Error:', error);
    }
  });
};

const sendMessage = () => {
  if (!newMessage.value && newMessage.value !== '') return;
  saveMessage(newMessage.value);
  chat(newMessage.value);
  newMessage.value = ""; // 清空输入框

  // 滚动到聊天区域的底部
  nextTick(() => {
    scrollToBottom();
  });
};

// 滚动到聊天记录的底部
const scrollToBottom = () => {
  if (messageArea) {
    messageArea.scrollTop = messageArea.scrollHeight;
  }
};

</script>


<style scoped>
/* 整体聊天容器 */
/* 整体聊天容器 */
.chat-container {
  background: #f5f5f5;
  display: flex;
  justify-content: center;  /* 水平居中 */
  align-items: center;      /* 垂直居中 */
  height: 100vh;
  padding: 0;
  border: 10px;
  overflow-x: hidden;       /* 禁止横向滚动 */
  box-sizing: border-box;
  flex-direction: column;   /* 容器方向为纵向 */
}

/* 聊天框 */
.chat-box {
  width: 100%;
  max-width: 700px;   /* 最大宽度为 700px */
  min-width: 400px;   /* 最小宽度为 400px */
  display: flex;
  flex-direction: column;   /* 垂直排列 */
  background-color: #fff;
  padding: 0;
  margin: 0;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  height: 100%;
  max-height: 100vh;
  position: relative;     /* 让输入框绝对定位在聊天框底部 */
}

/* 消息区域 */
.message-area {
  flex: 1;
  overflow-y: auto;
  max-height: calc(100vh - 120px); /* 留出空间给输入框 */
  width: 100%;
  overflow-x: hidden;        /* 禁止横向滚动 */
  box-sizing: border-box;
  padding: 15px 15px 70px;   /* 给消息区域和输入框留出空间 */

  /* 自定义滚动条样式 */
  scrollbar-width: thin;  /* Firefox 滚动条设置 */
  scrollbar-color: #888 #f0f0f0; /* Firefox 滚动条颜色 */

  /* 对于 WebKit 浏览器 (Chrome, Safari) */
  ::-webkit-scrollbar {
    width: 8px;
  }
  ::-webkit-scrollbar-thumb {
    background-color: #888;  /* 滚动条滑块颜色 */
    border-radius: 4px;  /* 滚动条滑块圆角 */
  }
  ::-webkit-scrollbar-track {
    background-color: #f0f0f0;  /* 滚动条轨道颜色 */
    border-radius: 4px;  /* 轨道圆角 */
  }
}

/* 单条消息 */
.message {
  margin-bottom: 80px; /* 增加消息间的间距 */
  display: flex;
  width: 100%;
}

/* 用户消息 */
.message.user {
  justify-content: flex-end;  /* 用户消息右对齐 */
  width: 100%;                 /* 使消息占满整行 */
}

/* 用户消息内容 */
.message.user .message-content {
  white-space: pre-wrap;
  background-color: #f0f0f0;  /* 用户消息的背景色 */
  border-radius: 12px;         /* 圆角 */
  padding: 20px;               /* 内边距 */
  max-width: 70%;

  word-wrap: break-word;
  word-break: break-word;      /* 强制单词换行，特别是没有空格的长单词 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  font-size: 16px;             /* 字体大小 */
}

/* 助手消息内容 */
.message.assistant .message-content {
  /*background-color: #f9f9f9;  !* 助手消息的背景色 *!*/
  border-radius: 12px;
  padding: 20px;
  max-width: 100%;
  word-wrap: break-word;       /* 长单词换行 */
  word-break: break-word;      /* 强制单词换行 */
  /*box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); !* 阴影效果 *!*/
  font-size: 16px;
}


/* 助手消息 */
.message.assistant {
  justify-content: flex-start;  /* 助手消息左对齐 */
  width: 90%;                  /* 使消息占满整行 */
}
/* 输入区域样式 */
.input-area {
  position: absolute;  /* 绝对定位 */
  bottom: 0;           /* 将输入区域固定在聊天框的底部 */
  left: 5px;
  width: 100%;         /* 输入框宽度与聊天框一致 */
  padding: 0;          /* 移除内边距 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;  /* 背景色 */
  height: 50px;  /* 固定输入区域高度 */
  box-sizing: border-box;
  z-index: 10;  /* 确保输入框位于上层 */
}

/* 输入框 */
.message-input {
  white-space: pre-wrap;
  bottom: 40px;
  width: 80%;  /* 输入框占输入区域宽度的80% */
  height: 50px;  /* 固定输入框的高度 */
  font-size: 16px;
  padding: 0;
  resize: none;  /* 禁止调整大小 */
  border-radius: 10px;  /* 圆角 */
  box-sizing: border-box;
  margin-right: 10px;  /* 输入框和按钮之间有一些间隔 */
}

/* 发送按钮 */
.send-btn {
  position: absolute;
  right: 20px;  /* 发送按钮右对齐 */
  bottom:40px;    /* 发送按钮紧贴输入区域底部 */
  width: 15%;
  height: 40px;  /* 固定发送按钮高度 */
  font-size: 16px;
  border-radius: 6px;
  background-color: #40b5dc;
  color: #fff;
  border: none;
}



</style>
